package com.edroid.apkhooker.db;

import java.io.IOException;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class ImeiDB {
	private static ImeiDB imeiDB;
	private Context context;
	private SQLiteDatabase db;
	private int imeiTotal;

	private ImeiDB() {
	}

	public static void init(Context context) throws IOException {
		if (imeiDB == null) {
			imeiDB = new ImeiDB();
			imeiDB.context = context;
			try {
				imeiDB.db = SQLiteDatabase.openDatabase(
						AssetsReleaseTool.releaseFile(context, "imeis.db"),
						null, SQLiteDatabase.OPEN_READONLY);
				Cursor cursor = imeiDB.db.rawQuery(
						"select count(*) from imeis", null);
				cursor.moveToFirst();
				imeiDB.imeiTotal = cursor.getInt(0);
				cursor.close();
			} catch (IOException exception) {
				imeiDB = null;
				exception.printStackTrace();
				throw exception;
			}
		}
	}

	public static ImeiDB getImeiDB() {
		return imeiDB;
	}

	public int getImeiTotal() {
		return imeiTotal;
	}

	/**
	 * 获得指定ID的IMEI
	 * 
	 * @param id
	 *            取值范围 [ 0 , {@link #getImeiTotal()} )
	 * @return IMEI
	 */
	public String getImeiById(int id) {
		Cursor cursor = db.rawQuery("select * from imeis where _id=" + id,
				null);
		String ret = null;
		if (cursor.moveToFirst()) {
			ret = cursor.getString(1);
		}
		cursor.close();
		return ret;
	}

	public SQLiteDatabase getDatabase() {
		return db;
	}
	
	public static void close() {
		if (imeiDB != null) {
			imeiDB.db.close();
			imeiDB = null;
		}
	}
}
